part of '../basic.dart';

extension ChineseNumberTransfer on int {
  /// 将整数转化为中文字符，比如13->十三，目前只支持0-50的整数
  String toChinese() {
    if (this < 0 || this > 50) {
      throw BugDev('只支持0-50的整数');
    }

    int number = this;

    if (number == 0) return '零';

    final units = ['', '十', '百', '千', '万', '亿'];
    final digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];

    String result = '';
    int unitPos = 0;
    bool needZero = false;

    while (number > 0) {
      int digit = number % 10;

      if (digit == 0) {
        if (result.isNotEmpty && !needZero) {
          result = digits[digit] + result;
          needZero = true;
        }
      } else {
        result = digits[digit] + units[unitPos] + result;
        needZero = false;
      }

      number ~/= 10;
      unitPos++;
    }

    // 处理“十”开头的情况，例如 12 应该是 “十二” 而不是 “一十二”
    if (result.startsWith('一十')) {
      result = result.substring(1);
    }

    return result;
  }
}
